package net.yunzhanyi.client.interceptor;

import com.alibaba.fastjson.JSON;
import net.yunzhanyi.client.annotation.AccountPublic;
import net.yunzhanyi.client.annotation.CheckLogin;
import net.yunzhanyi.client.service.TokenService;
import net.yunzhanyi.common.core.utils.StringUtils;
import net.yunzhanyi.common.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author bestct
 * @date 2022/10/3
 * @type 类
 */
@Component
public class AjaxLoginInterceptor implements AsyncHandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 拦截处理代码
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.getAnnotation(CheckLogin.class) == null) {
            if (method.getAnnotation(AccountPublic.class) != null) {
                tokenService.accountPublic(request);
            }
            return true;
        }
        String token = tokenService.getToken(request);
        if (StringUtils.isEmpty(token) || "null".equals(token) || "undefined".equals(token)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            String msg = "未登录,无法访问";
            AjaxResult error = AjaxResult.error(HttpStatus.UNAUTHORIZED.value(), msg);
            String jsonString = JSON.toJSONString(error);
            response.getWriter().print(jsonString);
            return false;
        }
        if (tokenService.verifyToken(token, request, response)) {
            return true;
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            String msg = "登录已过期";
            AjaxResult error = AjaxResult.error(HttpStatus.FORBIDDEN.value(), msg);
            String jsonString = JSON.toJSONString(error);
            response.getWriter().print(jsonString);
            return false;
        }
    }
}
